package com.jddup.program.comparator.mysql;

import com.jddup.common.pojo.TableColumn;
import com.jddup.program.comparator.AddColumnDDLBuilder;
import com.jddup.program.comparator.ColumnSqlBuilder;
import org.apache.commons.lang3.StringUtils;

public interface MysqlColumnSqlBuilder extends ColumnSqlBuilder {
    @Override
    default void buildColumnSql(TableColumn tableColumn, StringBuilder columnDDL) {
        String nullableString = tableColumn.getNullable() != null ? tableColumn.getNullable() ? "NULL" : "NOT NULL" : "";
        if (tableColumn.getPropertyType().equals(java.util.Date.class) ||
                tableColumn.getPropertyType().equals(java.sql.Time.class) ||
                tableColumn.getPropertyType().equals(java.sql.Date.class) ||
                tableColumn.getPropertyType().equals(java.sql.Timestamp.class) ||
                tableColumn.getPropertyType().equals(java.time.LocalDate.class) ||
                tableColumn.getPropertyType().equals(java.time.LocalTime.class) ||
                tableColumn.getPropertyType().equals(java.time.LocalDateTime.class)) {
            nullableString = "NULL";
        }
        String defaultString = tableColumn.getDefaultValue();
        String fullType = tableColumn.getTypeFullName();
        String primaryKeyString = tableColumn.getPrimaryKey() ? "PRIMARY KEY" : "";
        columnDDL
                .append("\n ").append(getQuote())
                .append(tableColumn.getColumnName().toLowerCase())
                .append(getQuote()).append(" ")
                .append(fullType);
        if (tableColumn.getPrimaryKey()) {
            columnDDL.append(" ").append(primaryKeyString);
        } else if (StringUtils.isNotBlank(nullableString)) {
            columnDDL.append(" ").append(nullableString);
        }
        if (StringUtils.isNotBlank(defaultString)) {
            columnDDL.append(" ").append(defaultString);
        }

        if (StringUtils.isNotBlank(tableColumn.getComment())) {
            columnDDL.append(" comment '").append(tableColumn.getComment().
                    replace("'", "").
                    replace("\"", "").
                    replace(" ", "").
                    replace("\n", "")).append("'");
        }
    }
}
